<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
class PlotfavController extends \App\Http\Controllers\AdminController{
    /**
     * 产品列表
     * @return type
     */
    public function index() {
        $plotfavs = \App\Models\Plotfav::leftJoin('dd_plot', 'dd_plotfav.plotid', '=', 'dd_plot.id')->leftJoin('dd_product', 'dd_plotfav.productid', '=', 'dd_product.id')->select("dd_plotfav.*", 'dd_plot.name as plotname', 'dd_product.name as productname', 'dd_product.ptype')->paginate();
        $assign = compact('plotfavs');
        return view('admin.plotfav.index', $assign);
    }
    /**
     * 修改/删除产品
     * @param Request $request
     * @param type $id
     * @param type $status
     * @return type
     */
    public function edit(Request $request, $id, $status=false) {
        $plotfav = \App\Models\Plotfav::find($id);
        if (!$plotfav) {
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 0,
                'info'      => '商品不存在'
            ]);
        }
        if ($status === '0') {
            $plotfav->delete();
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 1,
                'info'      => '删除成功'
            ]);
        }
        if ($request->ajax()) {
            $plotfav->plotfav = $request->input('plotfav');
            $plotfav->plotinit = $request->input('plotinit');
            $plotfav->save();
            return \Illuminate\Support\Facades\Response::json([
                'status'    => 1,
                'info'      => '修改成功'
            ]);
        }
        $assign = compact('plotfav');
        return view('admin.plotfav.edit', $assign);
    }
    /**
     * 添加新产品
     */
    public function add(Request $request) {
        if ($request->ajax()) {
            return \App\Models\Plotfav::addPlotfav($request);
        }
        $areas = \App\Models\Area::get();
        
        return view('admin.plotfav.add', ['areas'=>$areas]);
    }
    
    public function ppInfo($aid) {
        $plots = \App\Models\Plot::where("area", $aid)->whereIn('status', [1])->get();
        $product = \App\Models\Product::where("area", $aid)->whereIn('status', [1])->orderBy('ptype', 'asc')->get();
        if (count($product)) {
            foreach($product as $val) {
                $val->ptype = $val->strPtype();
                $products[] = $val;
            }
        } else {
            $products = "";
        }
        
        return \Illuminate\Support\Facades\Response::json(array("plots"=>$plots, "products"=>$products));
    }
}
